package com.ikaros.concurrency.example.syn;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SynchronizedClassAndStaticMethod {
    //修饰类
    private void expClass() {
        synchronized (SynchronizedClassAndStaticMethod.class) {
            for (int i = 0; i < 10; i++) {
                log.info("expClass-{}", i);
            }
        }
    }

    //修饰静态方法
    private static synchronized void expStaticMethod() {
        for (int i = 0; i < 10; i++) {
            log.info("expStaticMethod-{}", i);
        }
    }

    public static void main(String[] args) {
        SynchronizedClassAndStaticMethod synchronizedClassAndStaticMethod = new SynchronizedClassAndStaticMethod();
        SynchronizedClassAndStaticMethod synchronizedClassAndStaticMethodTwo = new SynchronizedClassAndStaticMethod();

        ExecutorService executorService = Executors.newCachedThreadPool();
        //修饰类和修饰静态方法【不同对象】单线程执行 ->作用于所有对象
        //ps:如果SynchronizedExp为父类,继承该类的子类调用父类的方法synchronized关键字无效
        executorService.execute(() -> {
            synchronizedClassAndStaticMethod.expStaticMethod();
        });
        executorService.execute(() -> {
            synchronizedClassAndStaticMethodTwo.expStaticMethod();
        });
    }
}
